<template>
	<!-- 拼单预览 -->
	<view class="e-p-t-20 e-p-l-20 e-p-r-20" :style="[AppSkinVar]">
		<e-loading-page :loading="loading||payLoading"  >
			<template #icon>
				<loader ></loader>
			</template>
		</e-loading-page>
		<order-address class="e-m-b-20" v-model:info="address" type="1" v-show="showAddress"></order-address>
		<SepllPerson v-if="info.orderGroup" :type="1" :groupInfo="info.orderGroup"></SepllPerson>
		<view class=" e-m-b-20">
			<goods-card v-for="(item, index) in info.orderVos" :key="index" :isJump="false" :store="item"
				:storeKeys="storeKeys" :goodsList="item.deputys" :goodsKeys="goodsKeys">
			</goods-card>
		</view>

		<view class="e-m-b-20 e-p-30 e-flex bg-white">
			<text class="e-m-r-76 c-secondary">{{ $t('classify.订单备注') }}</text>
			<e-input style="z-index: 1;" inputAlign="right" :placeholder="$t('classify.请填写备注信息')" border="none" v-model="remark"></e-input>
		</view>
		
		
		<view class="e-p-30 bg-white e-m-b-20">
			<view class="e-flex e-flex-between">
				<text class="c-secondary">{{ $t('order.商品总价') }}</text>
				<text>{{ $unitEn }}{{ info.money }}</text>
			</view>
			<view class="e-flex e-flex-between e-m-t-34">
				<text class="c-secondary">{{ $t('order.运费') }}</text>
				<text class="c-red">+{{ $unitEn }}{{ info.freight || info.deliveryfee }}</text>
			</view>
		</view>
		<view class="bg-white border-radius-20 overflow-hidd">
			<view class="e-p-l-20 e-p-r-20 e-p-t-25 e-p-b-25">
				<text class="fw-600">{{ $t('nearby.支付方式') }}</text>
			</view>
			<pay-list ref="payListRef" :isTrace="!!isTrace" :isDefault="isTrace ? 'N' : 'Y'" :proIds="proIds"></pay-list>
		</view>
		<password-popup ref="passwordPopupRef" :payMoney="info.payMoney" :show="show" @close="show = false" @confirm="passwordPay"></password-popup>


		<view style="height: 140rpx;"></view>
		<view class="fixed-button e-flex e-flex-between bg-white">
			<view class="e-flex e-flex-between">
				<text class="e-font-30">{{ $t('cart.总计') }}：</text>
				<text class="c-red e-font-36">{{ $unitEn }}{{ info.payMoney }}</text>
			</view>
			<button class="bg-primary c-white" @tap="buy">{{ $t('classify.去支付') }}</button>
		</view>
		<card-valid-code-popup :show="cardValidCodePopupShow" :payMoney="info.payMoney" @cancel="handleCancelCardPay" @confirm="handleCardPay"></card-valid-code-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, watch } from 'vue'
	import {
		throttle
	} from '@/common/utils'
	import {
		getPayResult,
		getAddressList,
		previewOrderGroup,
		createOrderGroup
	} from '@/common/request/api'
	import type { PreviewGroupOrderData, AddressItem, PurchaseGroupGoodsParams } from '@/common/request/api'
	import SepllPerson from './child/spellPerson.vue'
	import CardValidCodePopup from '../child/cardValidCodePopup.vue'
	import { useCurrentInstance } from '@/common/hooks'
	import type { Mutable } from '@/typings/utils'
	import { usePay } from '../hooks/usePay'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import type { PayListInstance, PasswordPopupInstance } from '@/typings/components';
	import { PayType } from '@/env'

	const props = defineProps({
		type: {
			type: String,
			required: true,
		},//下单类型 1单商品 2购物车 3多商品或订单重购买
		qty: String,//单商品下单参数
		groupCode:String,//参与拼团的code
		skuId: String,//单商品下单参数
		isTrace: String,// 是否来自视频带货
		receivingType: String
	})

	const pageParams : Partial<Mutable<typeof props>> = { ...props }
	delete pageParams.isTrace
	delete pageParams.type

	const ctx = useCurrentInstance()

	const { payLoading,
		systemPay,
		cardValidCodePopupShow,
		checkCardPay,
		handleCardPay,
		handleCancelCardPay,
		getH5PayResult } = usePay()

		const info = ref<PreviewGroupOrderData>({
		orderVos: [],
		storeReceiving: false,
		money: 0,
		moneyDis: 0,
		payMoney: 0,
		freight: 0,
		deliveryfee: 0,
		moneyDeduction: 0,
		couponMoney: 0,
		couponMoneySys: 0,
		deliveryModes: [],
		delivery: false
	})

	const loading = ref(true)


	const storeKeys = {
		name: 'storeName',
		logo: 'storeLogo'
	}
	const goodsKeys = {
		image: 'commodityUrl',
		skuName: 'commoditySpecName',
		price: 'deputyMoney',
		name: 'commodityName',
		qry: 'commodityCount'

	}

	const address = ref<AddressItem | undefined>(undefined)
	const show = ref(false)
	const showAddress = ref(true)

	const remark = ref('')// 订单备注
	
	const proIds = ref('');
	
	const getData = async () => {
		let params = {
			...pageParams,
			receivedId: address.value?.id,
			qty: props.qty || '',
			skuId: props.skuId || '',
		}


		try {
			const res = await previewOrderGroup(params)
			info.value = res.data
			const goodsType : number[] = []
			info.value.orderVos.forEach(item => {
				goodsType.push(...item.deputys.map(deputy => deputy.type))
				// 获取所有商品的id集
				proIds.value = item.deputys.map((item) => item.commodityId).join(',');
			})
			// 1 实物 2虚拟物品
			showAddress.value = goodsType.includes(1) || !goodsType.length
		} catch (e) {
			//TODO handle the exception
		}
		loading.value = false

	}

	watch(address, (newValue) => {
		if (newValue?.id && !loading.value) {
			getData()
		}
	})


	const payListRef = ref<PayListInstance>();

	const buy = throttle(function () {

		if (!address.value?.id) {
			ctx.$toastApp(ctx.$t('classify.请先添加收货地址再支付'))
			return
		}
		if (!payListRef.value?.payItem) {
			ctx.$toastApp(ctx.$t('nearby.请选择支付方式'));
			return;
		}
		// 如果支付金额为0，默认余额账户支付不用弹窗选择账户
		if (info.value.payMoney) {
			if (payListRef.value.payItem.type === 'SYS') {
				show.value = true;
			} else {
				pay(payListRef.value.payItem.id, undefined, payListRef.value.payItem.type);
			}
		} else {
			// 如果支付金额为0，默认取第一个支付方式，默认支付密码为sanxinjava
			//  如果有余额账号默认余额，没有则取第一个
			let arr = payListRef.value?.payMode?.filter((item) => item.isDefault === 'Y');
			if (!arr || !arr.length) {
				arr = payListRef.value?.payMode;
			}
			if (arr && arr.length) {
				const item = arr[0];
				pay(item.id, 'sanxinjava', PayType.SYS);
			} else {
				ctx.$toastApp(ctx.$t('order.平台暂未开放支付'));
			}
		}


	})
	
	const passwordPopupRef = ref<PasswordPopupInstance>();
	const passwordPay = (password: string) => {
		passwordPopupRef.value?.reset();
		show.value = false;
		pay(payListRef.value.payItem.id, password, payListRef.value.payItem.type);
	};
	// 支付
	const pay = throttle(async function (payId : number, payword : string | undefined = undefined, payType : PayType,bankId?:number) {
		let data : PurchaseGroupGoodsParams = {
			...pageParams,
			qty: props.qty || '',
			skuId: props.skuId || '',
			remark: remark.value,
			receivedId: address.value?.id,
			payId,
			fromType: getApp().globalData?.payFromType,
			payword,
			bankId
		}

		let requireOrder = false
		// #ifdef MP-WEIXIN
		if (props.isTrace) {
			let traceRes = await checkBeforeAddOrder()
			if (traceRes.code === 200) {
				data['traceId'] = traceRes.traceId
				requireOrder = traceRes.requireOrder === 1
			}
		}
		// #endif
		if(!bankId&&checkCardPay(payType,(cardId:number) => {
			pay(payId,payword, payType,cardId)
		})){
			return 
		}
		uni.hideLoading();
		const res = await createOrderGroup(data)
		payLoading.value = false
		await systemPay({
			payType,
			resolveData: res.data,
			api: getPayResult,
			storageKey: 'payOrderId',
			payUrl: res.data,
			payParams: res.data,
			successUrl: (paycode : string) => `spellGroup/pay-success/index?paycode=${paycode}`,
			errorUrl: (msg : string) => `order/error?msg=${msg}`,
			orderUrl: 'order/index?type=1',
			isTrace: !!props.isTrace,
			requireOrder,
			payMoney:info.value.payMoney
		})
	}, 1500)

	// #ifdef MP-WEIXIN
	const checkBeforeAddOrder = () : Promise<{
		traceId : string
		requireOrder : number
		code : number
	}> => {
		return new Promise((resolve, reject) => {
			wx.checkBeforeAddOrder({
				success: res => {
					resolve({
						traceId: res.data.traceId,
						requireOrder: res.data.requireOrder,
						code: 200
					})
				},
				fail: (err : any) => {
					reject({
						code: 500
					})
					console.log(err)
				}
			})
		})
	}
	// #endif


	onLoad(() => {

		getAddressList().then(res => {
			if (res.data.length) {
				address.value = res.data.find(item => item.isDefaul === 1)
			}
		}).finally(() => {
			getData()
		})
		// #ifdef HTML5 || PREVIEW
		getH5PayResult('pages/spellGroup/pay-success/index', 'payOrderId', getPayResult)
		// #endif
	})
</script>

<style lang="scss" scoped>
	.fixed-button {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 112rpx;
		padding: 0 28rpx;
		z-index: 1;

		button {
			width: 240rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			margin: 0;
		}
	}
</style>